package com.wdb007.venus.web.api.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.wdb007.venus.svc.facade.CouponService;
import com.wdb007.venus.svc.facade.UserService;
import com.wdb007.venus.svc.facade.coupon.model.CouponInfo;
import com.wdb007.venus.svc.facade.exception.BizException;
import com.wdb007.venus.svc.facade.model.VenusSvcResp;
import com.wdb007.venus.svc.facade.user.model.SmsVerifactionDTO;
import com.wdb007.venus.svc.facade.user.model.UserAccessLogDTO;
import com.wdb007.venus.svc.facade.user.model.UserEntiretyDTO;
import com.wdb007.venus.web.api.coupon.model.CouponRequest;
import com.wdb007.venus.web.api.coupon.model.DrawCouponRequest;
import com.wdb007.venus.web.api.model.BaseResponse;
import com.wdb007.venus.web.api.utils.RegExpValidatorUtils;

@Controller
@RequestMapping("/coupon/")
public class CouponController extends BaseController{

	private final static Logger logger = LoggerFactory.getLogger(CouponController.class);
	
	@Autowired
	private CouponService couponService;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/getCouponList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getCouponList(CouponRequest request) {
		logger.info("获取用户优惠券列表getCouponList request: {}", JSON.toJSONString(request));
		BaseResponse baseResponse = success();
		try {
			checkIsNull(request.getOper(), "oper");
			checkIsNull(request.getUserid(), "userid");
			List<CouponInfo> list = couponService.getCouponList(request.getOper(), request.getUserid());
			baseResponse.setItems(list);
			baseResponse.setTotalcount(list.size());
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		
		logger.info("获取用户优惠券列表getCouponList response: {}", JSON.toJSONString(baseResponse));
		return baseResponse ;
	}
	
	@RequestMapping(value="/getChargeCouponList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getChargeCouponList(CouponRequest request) {
		logger.info("获取支付页面优惠券列表getChargeCouponList request: {}", JSON.toJSONString(request));
		BaseResponse baseResponse = success();
		try {
			checkIsNull(request.getOper(), "oper");
			checkIsNull(request.getUserid(), "userid");
			if("3".equals(request.getOper())) {
				checkIsNull(request.getBookcaseId(), "bookcaseId");
			}
			List<CouponInfo> list = couponService.getChargeCouponList(request.getOper(), request.getUserid(), request.getAmount(), request.getBookcaseId());
			baseResponse.setItems(list);
			baseResponse.setTotalcount(list.size());
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("获取支付页面优惠券列表getChargeCouponList response: {}", JSON.toJSONString(baseResponse));
		return baseResponse ;
	}
	
	@RequestMapping(value="/drawCoupon", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse drawCoupon(DrawCouponRequest request, HttpServletRequest httpRequest) {
		logger.info("用户领取优惠券drawCoupon request: {}", JSON.toJSONString(request));
		BaseResponse baseResponse = success();
		try {
			checkIsNull(request.getMobile_no(), "mobile_no");
			checkIsNull(request.getCoupon_rule_id(), "coupon_rule_id");
			checkIsNull(request.getVerify_code(), "verify_code");
			//首先判断用户是否是领取新人券
			couponService.isNewUser(request.getCoupon_rule_id(), request.getMobile_no());
			
			//---------------判断用户验证码是否正确
			SmsVerifactionDTO smsVerifaction = new SmsVerifactionDTO();
			smsVerifaction.setMobileNo(request.getMobile_no());
			smsVerifaction.setSmsCode(request.getVerify_code());
			UserAccessLogDTO accessLog = new UserAccessLogDTO();
			//登录时usertoken，为wx_user_relation表中的id
			String wxUserRelationId = httpRequest.getParameter("usertoken");
			logger.info("wxUserRelationId: {}", wxUserRelationId);
			accessLog.setPartner(httpRequest.getHeader("source"));
			//活动请求的登录
			if(!isEmpty(httpRequest.getParameter("activityPartner"))) {
				accessLog.setPartner(httpRequest.getParameter("activityPartner"));
			}
			
			String ip = httpRequest.getHeader("X-Forwarded-For") ;
			if(null == ip || !RegExpValidatorUtils.isIP(ip)){
				ip = httpRequest.getRemoteAddr();
			}
			accessLog.setIp(ip);
			
			VenusSvcResp<UserEntiretyDTO> resp =  userService.login(smsVerifaction, accessLog, wxUserRelationId);
			if(resp.getRspCodeEnum() != null) {
				throw new BizException(resp.getRspCodeEnum());
			}
			Long userId = resp.getBody().getUserid();
			CouponInfo info = couponService.draw(userId, request.getCoupon_rule_id(), request.getU());
			baseResponse.setDetail(info);
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("用户领取优惠券drawCoupon response: {}", JSON.toJSONString(baseResponse));
		return baseResponse ;
	}
	
	@RequestMapping(value="/drawCouponV2", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse drawCouponV2(String coupon_rule_id, Long userid) {
		logger.info("用户领取优惠券drawCouponV2 coupon_rule_id: {}, userid: {}", coupon_rule_id, userid);
		BaseResponse baseResponse = success();
		try {
			CouponInfo info = couponService.draw(userid, coupon_rule_id);
			baseResponse.setDetail(info);
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("用户领取优惠券drawCouponV2 response: {}", JSON.toJSONString(baseResponse));
		return baseResponse ;
	}
	
	
	@RequestMapping(value="/getCouponRuleInfo", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getCouponRuleInfo(String coupon_rule_id) {
		logger.info("用户领取优惠券页面 优惠券规则getCouponRuleInfo coupon_rule_id: {}", coupon_rule_id);
		BaseResponse baseResponse = success();
		try {
			CouponInfo info = couponService.getCouponRuleInfo(coupon_rule_id);
			baseResponse.setDetail(info);
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("用户领取优惠券页面 优惠券规则getCouponRuleInfo response: {}", JSON.toJSONString(baseResponse));
		return baseResponse ;
	}
	
	@RequestMapping(value="/drawSpreadCoupon", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse drawSpreadCoupon(DrawCouponRequest request) {
		logger.info("用户领取地推券drawSpreadCoupon request: {}", JSON.toJSONString(request));
		BaseResponse baseResponse = success();
		try {
			CouponInfo info = couponService.draw(Long.valueOf(request.getUserid()), request.getCoupon_rule_id(), request.getU());
			baseResponse.setDetail(info);
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("用户领取地推券drawSpreadCoupon response: {}", JSON.toJSONString(baseResponse));
		return baseResponse ;
	}
	
	@RequestMapping(value="/scanQrCode", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse scanQrCode(DrawCouponRequest request) {
		logger.info("用户扫描地推券scanQrCode request: {}", JSON.toJSONString(request));
		BaseResponse baseResponse = success();
		try {
			couponService.scanQrCode(request.getCoupon_rule_id(), request.getU());
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("用户扫描地推券scanQrCode response: {}", JSON.toJSONString(baseResponse));
		return baseResponse ;
	}
}
